package com.fairytask.ui
{
	import com.fairytask.data.RecordObject;
	import com.fairytask.data.ViewObject;
	import com.fairytask.engine.components.ToolTips;
	import com.fairytask.engine.components.button.Button;
	import com.fairytask.engine.components.clip.Clip;
	import com.fairytask.engine.components.group.ViewGroup;
	import com.fairytask.engine.components.text.Label;
	import com.fairytask.engine.components.text.Text;
	import com.fairytask.engine.define.CoolDefine;
	import com.fairytask.managers.TipsManage;
	import com.fairytask.resource.StaticIni;
	import com.fairytask.tools.SystemTime;
	import com.fairytask.ui.base.FrameUI;
	import com.fairytask.ui.item.BagItemBak;
	import com.fairytask.ui.item.TimeShow;
	import com.fairytask.ui.item.pet.NineItem;
	import com.fairytask.ui.item.pet.PetEggWordItem;
	import com.greensock.TimelineLite;
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	
	/**
	 * 猎宠UI 
	 * @author xujh
	 * 
	 */
	public class GetPetsUI extends FrameUI
	{
		private static var _self		:GetPetsUI;
		
		public var timeBG		:MovieClip;
		public var infoBG		:MovieClip;
		public var freeBG		:MovieClip;
		
		public var timeLab		:Clip;		//刷新时间
		public var timeshow	:TimeShow;	//冷却时间
		public var timeBtn		:Button;	//立即刷新
		public var petEggVG	:ViewGroup;	//宠物蛋容器
		public var freeEgg		:BagItemBak;//免费宠物蛋
		
		public var petInfo		:Text;		//猎宠描述
		public var refreshBtn	:Button;	//刷新全部
		public var stiLab		:Label;		//体力
		public var stiInfo		:Text;		//体力说明
		public var getFreeInfo	:Text;		//X次后获取
		
		private var nineWrod	:NineItem;
		private var _nineInit	:Boolean = false;	//首次9字（直接显示）
		private var _isPlay		:Boolean = false;	//在播放动画
		
		private var _unbind	:Array = [];//用于解绑
//		private var _bindRec	:Array = [];
		private var _freeStr	:String = StaticIni.getSwfLangStr("1000000309");
		private var _payStr	:String = StaticIni.getSwfLangStr("1000000204");
		private var _freeID	:int;	//免费获取宠物id
		private var _timeNum	:int = -1;	//点击次数
		private var _time		:int;
		private var _startTime	:int;
		//免费宠物蛋动画
		private var _eggTimeLine	:TimelineLite = new TimelineLite({repeat:-1});
		//可以获取免费宠物蛋
		private var _canGetFree	:Boolean = false;
		
		//扣除体力
		private var _STSubLab	:Label = new Label("FF0000",12);
		private var _STVal		:int;	//体力值
		//cacheDate
		private var _cacheWord	:Array	=	null;
		
		
		public static function getInstance():GetPetsUI
		{
			if (_self == null)
			{
				_self=new GetPetsUI;
			}
			return _self;
		}
		
		public function GetPetsUI(popUI:Boolean=true)
		{
			super(popUI);
			init();
			initEggs();
			initEvent();
			initBind();
		}
		
		private function init():void
		{
			//冷却时间初始化
			timeshow = new TimeShow(0,"ff0000",null,1);
			timeshow.x = 410;
			timeshow.y = 40;
			timeshow.setTimer(false);
			timeshow.styleColor("00FF00");
			windowBG.addChild(timeshow);
			
			//九格真言
			nineWrod = new NineItem();
			nineWrod.x = 150;
			nineWrod.y = 260;
			windowBG.addChild(nineWrod);
			
			freeEgg = new BagItemBak();
			freeEgg.hasItemBg = true;
			freeEgg.x = 445;
			freeEgg.y = 352;
			windowBG.addChild(freeEgg);
			
			//动画时间轴初始化
			_eggTimeLine.append(TweenMax.to(freeEgg, 0.2, {glowFilter:{color:0xFFFFFF, alpha:0.7, blurX:15, blurY:15, strength:1.5, quality:1},repeat:-1,yoyo:true,startAt:{glowFilter:{color:0xFFFFFF, alpha:0.2, blurX:0, blurY:0, strength:1, quality:1}}}));
			_eggTimeLine.stop();
			
			_STSubLab.x = 85;
			_STSubLab.y = 260;
			windowBG.addChild(_STSubLab);
			_STSubLab.alpha = 0;
		}
		
		/**
		 * 初始化宠物蛋 
		 * 
		 */
		private function initEggs():void
		{
			var tmpItem :PetEggWordItem;
			for(var i:int=0;i<4;i++)
			{
				tmpItem = new PetEggWordItem();
				petEggVG.getItemByIndex(i).addItem(tmpItem);
				tmpItem.x = tmpItem.y = 5;
			}
		}
		
		private function initEvent():void
		{
			timeBtn.addEventListener(MouseEvent.CLICK,onPayTime);
			refreshBtn.addEventListener(MouseEvent.CLICK,onRefresh);
			refreshBtn.addEventListener(MouseEvent.MOUSE_OVER,onOver);
			refreshBtn.addEventListener(MouseEvent.MOUSE_OUT,onOut);
			//九格点击
			nineWrod.addItemEvent(MouseEvent.CLICK,onClickNine);
			//宠物蛋点击
			petEggVG.addItemsEvent(MouseEvent.CLICK,onGetPet);
			//免费宠物蛋
			freeEgg.addEventListener(MouseEvent.CLICK,onClickFree);
			freeEgg.addEventListener(MouseEvent.MOUSE_OVER,onFreeOver);
			freeEgg.addEventListener(MouseEvent.MOUSE_OUT,onOut);
			//倒计时结束
			timeshow.addEventListener(TimerEvent.TIMER_COMPLETE,timeComplete);
			
			//可以免费获得一个宠物
			//model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_GET_PET,onGetFree);
			//刷新宠物
			//model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_REFESH_PET,onTimeBtn);
			//刷新九字真言
			//model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_REFESH_WORD,onFreshBtn);
			//刷新九字真言特效
			//model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_REFRESH_MSG,onNineFlash);
		}
		
		/**
		 * 九字动画点亮 
		 * @param evt
		 * 
		 */
		/*private function onNineFlash(evt:CustomToClientEvent):void
		{
			if(_isPlay)
			{
				_cacheWord	=	evt.pList;
				return;
			}
			var type	:int = evt.pList.shift();
			//处理真言数据
			var wordArr	:Array	=	formatData(evt.pList);
			//取数据出错
			if(wordArr.length == 0)
			{
				return;
			}
			//新手引导或第一次显示
			if(type == 1 || !_nineInit)
			{
				_nineInit = true;
				nineWrod.clearAll();
				for(var i:int=0;i<3;i++)
				{
					nineWrod.setState(wordArr.shift(),1);
				}
				nineWrod.showAllMoney();
			}
			else
			{
				refreshBtn.enabled = false;
				_isPlay	=	true;
				nineWrod.playAnime(wordArr,onPlayOver);
			}
		}*/
		
		/**
		 * 格式化数据
		 * @param val 传输过来的数组
		 * @return 返回点亮的数组
		 * 
		 */
		private function formatData(val:Array):Array
		{
			var arr	:Array	=	[];
			nineWrod.clearMoney();
			while(val.length > 0)
			{
				var pos		:int	=	val.shift() - 1;
				var state	:int	=	val.shift();
				var value	:int	=	val.shift();
				//显示字
				nineWrod.setWord(pos,pos+1);
				if(state == 1)
				{
					arr.push(pos);
				}
				if(value != 0)
				{
					nineWrod.setMoney(pos,value);
				}
			}
			return arr;
		}
		
		/**
		 * 改变9字状态 
		 * @param key
		 * @param val
		 * @param pList
		 * 
		 */
		private function changeNineWord(key:String,val:int,pList:Array):void
		{
			var pos	:int	=	pList[0];
			//0是字，1是状态,2是价格
			if(key == "0")
			{
				nineWrod.setWord(pos,val);
			}
			else if(key == "2")
			{
				if(!_nineInit)
				{
					nineWrod.setMoney(pos,val,true);
				}
				else
				{
					nineWrod.setMoney(pos,val);
				}
			}
			else if(key == "1" && !_nineInit)
			{
				nineWrod.setState(pos,val);
			}
		}
		
		/**
		 * 播放完动画 
		 * 
		 */
		private function onPlayOver():void
		{
			refreshBtn.enabled = true;
			_isPlay	=	false;
			if(null != _cacheWord)
			{
				//model.dispatchEvent(new CustomToClientEvent(CustomToClientEvent.SERVER_CUSTOMMSG_REFRESH_MSG,_cacheWord));
				_cacheWord = null;
			}
		}	
		
		/**
		 * 刷新九字真言
		 * @param event
		 * 
		 */
		/*private function onFreshBtn(evt:CustomToClientEvent):void
		{
			refreshBtn.enabled = true;
		}*/
		
		/**
		 * 刷新宠物
		 * @param event
		 * 
		 */
		/*private function onTimeBtn(evt:CustomToClientEvent):void
		{
			timeBtn.enabled = true;
		}*/
		
		/**
		 * 免费宠物tips
		 * @param event
		 * 
		 */
		private function onFreeOver(event:MouseEvent):void
		{
			TipsManage.petEggTips(_freeID);
		}
		
		/**
		 * 绑定数据 
		 * 
		 */
		private function initBind():void
		{
			//猎宠视图
			//bindManager.BindView(model.scene,ViewDefine.VIEWPORT_PET_GET_BOX,addPetEgg,removePetEgg);
			//9格真言表格
//			bindManager.BindRecord(model.scene,RecordDefine.WORDRES,addWord,removeWord);
			//绑定冷却时间
			//bindManager.BindRecord(model.scene,RecordDefine.COOLREC,onAddTime,onRemoveTime);
			//绑定体力值
			//bindManager.BindProp(Player.instance.data, "ST",this,"rST")
		}
		
		/**
		 * 添加猎宠宠物蛋
		 * @param key
		 * @param val
		 * @param data
		 * 
		 */
		private function addPetEgg(key:String, val:ViewObject, data:Object):void
		{
			var pos	:int = val.GetPropertiesEx("Pos") - 1;
			var id	:int = val.GetPropertiesEx("ConfigID");
			//configID不为空
			if(id == 0)
			{
				return;
			}
			var tmpItem :PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
			tmpItem.data = val;
			//绑定数据
			_unbind[pos] = [];
			//字的状态
			/*_unbind[pos].push([val,"State1",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"State1",changeState,null,[pos,0])]);
			_unbind[pos].push([val,"State2",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"State2",changeState,null,[pos,1])]);
			_unbind[pos].push([val,"State3",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"State3",changeState,null,[pos,2])]);
			_unbind[pos].push([val,"State4",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"State4",changeState,null,[pos,3])]);
			//文字
			_unbind[pos].push([val,"Pos1",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"Pos1",changeWord,null,[pos,0])]);
			_unbind[pos].push([val,"Pos2",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"Pos2",changeWord,null,[pos,1])]);
			_unbind[pos].push([val,"Pos3",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"Pos3",changeWord,null,[pos,2])]);
			_unbind[pos].push([val,"Pos4",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"Pos4",changeWord,null,[pos,3])]);
			//CanGet  0不可以，1可以
			_unbind[pos].push([val,"CanGet",bindManager.BindPropInViewObj(model.scene.GetView(ViewDefine.VIEWPORT_PET_GET_BOX),key,"CanGet",changeGet,null,[pos])]);*/
		}
		
		/**
		 * 移除宠物蛋 
		 * @param key
		 * @param val
		 * @param data
		 * 
		 */
		private function removePetEgg(key:String, val:ViewObject, data:Object):void
		{
			var pos	:int = val.GetPropertiesEx("Pos") - 1;
			var id	:int = val.GetPropertiesEx("ConfigID");
			var tmpItem :PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
			tmpItem.clear();
			tmpItem.data = null;
			
			//解绑数据
			var arr :Array = _unbind[pos];
			for each(var itemBind:Array in arr)
			{
				bindManager.UnbindProp(itemBind.shift(),itemBind.shift(),itemBind.shift());
			}
		}
		
		/**
		 * 9字真言设置文字级状态 
		 * @param key
		 * @param val
		 * 
		 */
		/*private function addWord(key:String, val:RecordObject):void
		{
			var pos	:int = int(key);
//			nineWrod.setState(int(key),val.GetPropertiesEx("0"),val.GetPropertiesEx("1"));
			//绑定数据
			_bindRec[pos] = [];
			_bindRec[pos].push([val,"0",bindManager.BindRecordProp(val,"0",changeNineWord,[pos])]);
			_bindRec[pos].push([val,"1",bindManager.BindRecordProp(val,"1",changeNineWord,[pos])]);
			_bindRec[pos].push([val,"2",bindManager.BindRecordProp(val,"2",changeNineWord,[pos])]);
		}*/
		
		/**
		 * 9字删除 
		 * @param key
		 * @param val
		 * 
		 */
		/*private function removeWord(key:String, val:RecordObject):void
		{
			var pos	:int = int(key);
			//解绑数据
			var arr :Array = _bindRec[pos];
			for each(var itemBind:Array in arr)
			{
				bindManager.UnbindProp(itemBind.shift(),itemBind.shift(),itemBind.shift());
			}
		}*/
		
		/**
		 * 冷却时间 
		 * @param key
		 * @param val
		 * 
		 */
		private function onAddTime(key:String, val:RecordObject):void
		{
			if(val.GetProperties("0")==CoolDefine.COOL_DOWN_PET)
			{
				bindManager.BindRecordProp(val,"1",setCool);
				bindManager.BindRecordProp(val,"2",setCool);
				bindManager.BindRecordProp(val,"3",setBtn);
			}
		}
		
		private function onRemoveTime(key:String, val:RecordObject):void
		{
			
		}
		
		/**
		 * 设置冷却时间 
		 * @param key
		 * @param val
		 * 
		 */
		private function setCool(key:String,val:int):void
		{
			//1是冷却时间，2是开始时间
			if(key == "1")
			{
				_time = val;
			}
			else
			{
				_startTime = val;
			}
			if(_time == 0 || _startTime == 0)
			{
				return;
			}
			timeshow.time = SystemTime.getLeftTime(_startTime*1000,_time*1000)/1000;
		}
		
		/**
		 * 设置冷却状态 
		 * @param key
		 * @param val
		 * 
		 */
		private function setBtn(key:String,val:int):void
		{
			if(val<2)
			{
				//按钮文字及冷却时间颜色
				timeBtn.label = _freeStr;
				timeshow.styleColor("00FF00");
			}
			else
			{
				timeBtn.label = _payStr;
				timeshow.styleColor("FF0000");
			}
		}
		
		/**
		 * 改变状态 
		 * @param val
		 * @param key
		 * 
		 */
		private function changeState(key:String,value:int,pList:Array):void
		{
			var pos	:int	=	pList[0];
			var num	:int	=	pList[1];
			var tmpItem	:PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
			tmpItem.setStatus(num,value);
		}
		
		/**
		 * 改变文字 
		 * @param val
		 * @param key
		 * 
		 */
		private function changeWord(key:String,value:int,pList:Array):void
		{
			var pos	:int	=	pList[0];
			var num	:int	=	pList[1];
			var tmpItem	:PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
			tmpItem.setWord(num,value);
		}
		
		/**
		 * 改变领取状态 
		 * @param key
		 * @param value
		 * @param pList
		 * 
		 */
		private function changeGet(key:String,val:int,pList:Array):void
		{
			var pos	:int	=	pList[0];
			var tmpItem	:PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
			tmpItem.canGet = Boolean(val);
		}
		
		/**
		 * 立即刷新 
		 * @param evt
		 * 
		 */
		private function onPayTime(evt:MouseEvent):void
		{
			if(timeBtn.label == _freeStr)
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_PET_FREE_REFRESH);
			}
			else
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_PET_PAY_REFRESH);
			}
			timeBtn.enabled = false;
		}
		
		/**
		 * 刷新全部
		 * @param evt
		 * 
		 */
		private function onRefresh(evt:MouseEvent):void
		{
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_WORD_REFRESH);
			refreshBtn.enabled = false;
		}
		
		/**
		 * 显示消耗tips 
		 * @param evt
		 * 
		 */
		private function onOver(evt:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStr("1000000430"));
		}
		
		/**
		 * 隐藏tips 
		 * @param evt
		 * @param pos
		 * 
		 */
		private function onOut(evt:MouseEvent):void
		{
			ToolTips.hide();
		}
		
		/**
		 * 九格点击
		 * @param evt
		 * 
		 */
		private function onClickNine(evt:MouseEvent,pos:int):void
		{
			//播放动画时不处理
			if(_isPlay || null!=_cacheWord)
			{
				return;
			}
			if(nineWrod.checkState(pos))
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_WORD_ROW_NUMBER,pos);
			}
			else
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_BUY_WORD_ROW_NUMBER,pos);
			}
		}
		
		/**
		 * 获取宠物蛋 
		 * @param evt
		 * @param pos
		 * 
		 */
		private function onGetPet(evt:MouseEvent,pos:int):void
		{
			if(null != petEggVG.getItemByIndex(pos).getItem())
			{
				var tmpItem	:PetEggWordItem = petEggVG.getItemByIndex(pos).getItem() as PetEggWordItem;
				if(tmpItem.canGet)
				{
					//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GET_PET_BY_WORD,pos+1);
				}
			}
			
		}
		
		/**
		 * 点击免费宠物 
		 * @param evt
		 * 
		 */
		private function onClickFree(evt:MouseEvent):void
		{
			if(_timeNum == 0)
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GET_PET,_freeID);
			}
		}
		
		/**
		 * 倒计时结束，更新冷却 
		 * @param evt
		 * 
		 */
		private function timeComplete(evt:TimerEvent):void
		{
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_COOLDOWN_END);
			
		}
		
		/**
		 * 可以免费获得一个宠物 
		 * @param evt
		 * 
		 */
		/*private function onGetFree(evt:CustomToClientEvent):void
		{
			_freeID		= evt.pList.shift();
			_timeNum	= evt.pList.shift();
			freeEgg.source = ResConfig.iconPath + StaticIni.getIniVar(_freeID,"Icon") + ResConfig.iconImg;
			getFreeInfo.htmlStr = StaticIni.getSwfLangStrVar("1000000308",[_timeNum]);
			//可以免费领取
			if(_timeNum == 0)
			{
				_canGetFree = true;
				freeEgg.buttonMode = true;
				_eggTimeLine.play();
			}
			else if(_canGetFree)
			{
				_canGetFree = false;
				freeEgg.buttonMode = false;
				_eggTimeLine.stop();
				freeEgg.filters = null;
			}
		}*/
		
		/**
		 * 体力 
		 * @param val
		 * 
		 */
		public function set rST(val:int):void
		{
			//等于0
			if(_STVal == 0)
			{
				stiLab.htmlStrByBorder = StaticIni.getSwfLangStr("1000000214") + val;
				_STVal = val;
				return;
			}
			//体力值不等播放扣除动画
			if(_STVal != val)
			{
				_STSubLab.htmlStr = "-" + (_STVal - val);
				_STSubLab.y = 260;
				_STSubLab.alpha = 1;
				TweenLite.to(_STSubLab,1,{alpha:0.5,y:255,onComplete:onAlpha});
				_STVal = val;
			}
//			stiLab.htmlStrByBorder = StaticIni.getSwfLangStr("1000000214") + val;
		}
		
		/**
		 * 体力动画完成
		 * 
		 */
		private function onAlpha():void
		{
			_STSubLab.alpha = 0;
			stiLab.htmlStrByBorder = StaticIni.getSwfLangStr("1000000214") + _STVal;
		}
		
		override protected function BeforeShow():void
		{
			timeBtn.enabled		=	true;
			refreshBtn.enabled	=	true;
			_cacheWord = null;
		}
	}
}